package com.grailslm.json

import groovy.json.JsonSlurper

class JsonString2JsonPathMap {
    def dsObject // a data structure of lists and maps
    LinkedHashMap resultMap = new LinkedHashMap() // JsonPathMap（使用LinkedHashMap，比较容易人工校对）

    JsonString2JsonPathMap(String strJson) {
        this.dsObject = new JsonSlurper().parseText(strJson) // Eval.x(this.dsObject, "x.data.n_1_1")
    }

    /**
     * 执行入口
     */
    LinkedHashMap exec() {
        this.handleObject(this.dsObject)
        return this.resultMap
    }

    /**
     * 路由->子入口点
     */
    private void handleObject(Object object) {
        if(object instanceof Map) {
            this.handleMap("x", object)
        } else if (object instanceof List) {
            this.handleList("x", object)
        } else {
            println "暂不处理"
        }
    }

    /**
     * map处理
     */
    private void handleMap(String parentJsonPath, Map map) {
        map.each {key, instance->
            def jsonPath = "${parentJsonPath}.${key}"
            if(instance instanceof Map) {
                this.handleMap(jsonPath, instance)
            } else if(instance instanceof List) {
                this.handleList(jsonPath, instance)
            } else {
                resultMap.put(jsonPath, instance)
            }
        }
    }

    /**
     * list处理
     */
    private void handleList(String parentJsonPath, List list) {
        list.eachWithIndex {instance, index->
            def jsonPath = "${parentJsonPath}[${index}]"
            if(instance instanceof Map) {
                this.handleMap(jsonPath, instance)
            } else if(instance instanceof List) {
                this.handleList(jsonPath, instance)
            } else {
                resultMap.put(jsonPath, instance)
            }
        }
    }

    static main(args) {
        println new JsonString2JsonPathMap(this.getResourceAsStream("source.json").text).exec()
    }
}
